package com.demo.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.demo.entity.User;
import com.demo.service.BaseService;
import com.demo.util.MD5Util;

@Controller
@RequestMapping(value = "/")
public class IndexController {

	@Resource
	private BaseService<User> userService;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView login(ModelAndView modelAnView) {
		modelAnView.setViewName("index/login");
		return modelAnView;
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelAndView logon(ModelAndView modelAnView, HttpServletRequest req,
			@RequestParam(name = "username", required = true) String username,
			@RequestParam(name = "password", required = true) String password) {
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username, MD5Util.getMD5(password).toCharArray());
		token.setRememberMe(true);
		try {
			subject.login(token);
			modelAnView.setViewName("redirect:/index");
			return modelAnView;
		}catch (AuthenticationException e) {
			token.clear();
			modelAnView.setViewName("redirect:/login");
			return modelAnView;
		}
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public ModelAndView logout(ModelAndView modelAndView) {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		modelAndView.setViewName("index/login");
		return modelAndView;
	}
	
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public ModelAndView index(ModelAndView modelAnView) {
		modelAnView.setViewName("index/index");
		return modelAnView;
	}
}
